package com.web.oa.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.web.oa.pojo.ActiveUser;
import com.web.oa.service.EmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class LoginController {
    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/checkCodeServlet")
    public ResponseEntity<byte[]> generateVerifyCode(HttpSession session) throws IOException {

        // 使用 hutool 工具类生成验证码
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(120, 50, 4, 20);
        //captcha.setFont(new Font("Arial", Font.BOLD, 48));
        // 将验证码结果存入 Sesstion 中
        session.setAttribute("vaildCode", captcha.getCode());
        System.out.println("captcha.getCode():"+captcha.getCode());
        return new ResponseEntity<>(captcha.getImageBytes(), HttpStatus.OK);
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, Model model) throws IOException {

        String exceptionName = (String) request.getAttribute("shiroLoginFailure");

        System.out.println("exceptionName:"+exceptionName);
        if (exceptionName != null) {
            if (UnknownAccountException.class.getName().equals(exceptionName)) {
                model.addAttribute("errorMsg", "账号不存在"); // 该异常会被springmvc的异常处理器收集统一处理，跳转到error.jsp 给出提示
            } else if (IncorrectCredentialsException.class.getName().equals(exceptionName)) {
                model.addAttribute("errorMsg", "密码错误");
            } else if ( exceptionName.equals("InValidateCode") ) {
                model.addAttribute("errorMsg", "验证码错误");
            } else {
                model.addAttribute("errorMsg", "未知错误");
            }
        }
        return "login";
    }

    @RequestMapping("/main")
    public String main(ModelMap model){
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        model.addAttribute("activeUser",activeUser);
        return "index";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:login.jsp";
    }
}
